package com.ky.manage.utils.http;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.ky.manage.BaseApplication;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.LoginResp;
import com.ky.manage.utils.MMKVUtil;
import com.ky.manage.utils.SharedPreferencesUtil;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

import cz.msebera.android.httpclient.Header;

/**
 * 业务接口请求
 */
public class BusinessHttpReqUtils {
    private static BusinessHttpReqUtils mInstance;
    public static final String SERVICE_DOMAIN = "https://www.keyifazhan.com"; //"http://348m2940t9.eicp.vip"

    private BusinessHttpReqUtils() {
    }

    public static BusinessHttpReqUtils getInstance() {
        if (mInstance == null) {
            synchronized (BusinessHttpReqUtils.class) {
                if (mInstance == null) {
                    mInstance = new BusinessHttpReqUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * 退出登陆
     */
    public void logout() {
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/logout", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("logout", "onFailure statusCode = " +
                        statusCode + ", responseString = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("logout", "onSuccess statusCode = " +
                        statusCode + ", responseString = " + responseString);
                if (statusCode == 200) {
                    ToastUtils.showRoundRectToast("已退出登录");
                    BaseApplication.updateLoginUserInfo(null);
                }
            }
        });
    }

    /**
     * 自动密码登陆： token失效时
     * @param context
     */
    public void autoPwdLogin(Context context) {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null != loginUserInfo && !TextUtils.isEmpty(loginUserInfo.pwd) && !TextUtils.isEmpty(loginUserInfo.phone)) {
            requestLogin(context, loginUserInfo.phone, loginUserInfo.pwd, new TextHttpResponseHandler(){
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    //请求成功回调
                    //自动登陆成功
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      String responseString, Throwable throwable) {
                    //请求失败
                    ToastUtils.showRoundRectToast("登录失效，请重新登陆");
                    BaseApplication.updateLoginUserInfo(null);
                }

            });
        } else {
            BaseApplication.updateLoginUserInfo(null);
        }
    }

    /**
     * 登录接口调用
     * @param context
     * @param userName
     * @param pwd
     * @param callback
     */
    public void requestLogin(Context context, String userName, String pwd, TextHttpResponseHandler callback) {
        ZyUtils.getInstance().insertLog("requestLogin", "userName = " + userName + ", pwd = " + pwd);
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(pwd)) {
            ToastUtils.showRoundRectToast("请完善登录信息");
            return;
        }
        JSONObject loginReq = new JSONObject();
        try {
            loginReq.put("username", userName);
            loginReq.put("password", pwd);
        } catch (JSONException e) {

        }
        AsyncHttpUtils.getInstance().postJson(context, SERVICE_DOMAIN + "/appApi/login", loginReq, new TextHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                //请求成功回调
                LoginResp loginResp = parseJsonObj(responseString, LoginResp.class);
                ZyUtils.getInstance().insertLog("requestLogin", "onSuccess statusCode = "
                        + statusCode + ", response = " + responseString);
                if (null != loginResp && loginResp.code == 200) {
                    //登录成功, 获取用户信息
                    saveToken(loginResp.token);
                    if (null != callback) {
                        callback.onSuccess(statusCode, headers, responseString);
                    }
                } else {
                    ToastUtils.showRoundRectToast("登录失败");
                    if (null != callback) {
                        callback.onFailure(-1, headers, "", new Throwable("登陆失败"));
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                //请求失败
                ZyUtils.getInstance().insertLog("requestLogin", "onFailure response = " + responseString);
                ToastUtils.showRoundRectToast("登录失败：" + throwable.getMessage());
                if (null != callback) {
                    callback.onFailure(statusCode, headers, responseString, throwable);
                }
            }

        });
    }

    /**
     * 获取用户信息: 只解析用户基本信息：用户名、手机号、头像
     * @param context
     * @param callback
     */
    public void requestLoginUserInfo(Context context, TextHttpResponseHandler callback) {
        ZyUtils.getInstance().insertLog("requestLoginUserInfo", "start token = "
                + getToken());
        AsyncHttpUtils.getInstance().get(context, SERVICE_DOMAIN + "/appApi/getUserInfo", callback);
    }

    /**
     * 获取用户详细信息: 客户管理模块，获取客户信息列表，筛选获取
     * @param requestParams
     */
    public void requestUserDetailInfo(RequestParams requestParams, TextHttpResponseHandler callback) {
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getUserList", requestParams, callback);
    }

    /**
     * 获取区域数据
     * @param requestParams
     * @param callback
     */
    public void getAreaList(RequestParams requestParams, TextHttpResponseHandler callback) {
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getAreaList", requestParams, callback);
    }

    /**
     * 获取检修条目列表
     * @param indoorId
     * @param callback
     */
    public void requestIndoorCheckItemListInfo(String indoorId, TextHttpResponseHandler callback) {
        if (ZyUtils.getInstance().isNetConnected() && !TextUtils.isEmpty(indoorId)) {
            RequestParams requestParams = new RequestParams();
            requestParams.add("indoorId", indoorId);
            AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getProjectList", requestParams, callback);
        }
    }

    /**
     * 获取户外检测项目
     * @param lineId
     * @param callback
     */
    public void requestOutdoorCheckItemListInfo(String lineId, TextHttpResponseHandler callback) {
        if (ZyUtils.getInstance().isNetConnected() && !TextUtils.isEmpty(lineId)) {
            AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getLineProject/" + lineId, callback);
        }
    }

    /**
     * 通用文件上传接口
     * @param file
     * @param callback
     */
    public void uploadFile(File file, TextHttpResponseHandler callback) {
        ZyUtils.getInstance().insertLog("zhaoyan", "uploadFile start");
        if (null == file || !file.exists()) {
            ZyUtils.getInstance().insertLog("zhaoyan", "uploadFile 文件不存在");
            return;
        }
        RequestParams params = new RequestParams();
        try {
            params.put("file", file);
        } catch (FileNotFoundException e) {
            ZyUtils.getInstance().insertLog("zhaoyan", "uploadFile e = " + e.toString());
        }
        AsyncHttpUtils.getInstance().uploadFile(SERVICE_DOMAIN + "/appApi/common/upload", params, callback);
    }

    public void changeUserHeaderImg(File file, TextHttpResponseHandler callback) {
        if (null == file || !file.exists()) {
            return;
        }
        RequestParams params = new RequestParams();
        try {
            params.put("avatarfile", file);
        } catch (FileNotFoundException e) {
            ZyUtils.getInstance().insertLog("changeUserHeaderImg", "e = " + e.toString());
        }
        AsyncHttpUtils.getInstance().uploadFile(SERVICE_DOMAIN + "/appApi/uploadAvatar", params, callback);
    }


    public void saveToken(String token) {
        if (TextUtils.isEmpty(token)) {
            return;
        }
        SharedPreferencesUtil.saveStringData("token", token);
        MMKVUtil.getInstance().saveStringToMMKV("token", token);
    }

    public String getToken() {
        return MMKVUtil.getInstance().readStringFromMMKV("token", "");
    }

    public <T> T parseJsonObj(String jsonStr, Class<T> clazz) {
        if (TextUtils.isEmpty(jsonStr)) {
            return null;
        }
        T obj = null;
        try {
            obj = new Gson().fromJson(jsonStr, clazz);;
        } catch (Exception e) {

        }
        return obj;
    }
}
